package com.icehelper.hades.base.log;

import java.util.List;


public class SpanIdGenerator {

  private static long ipFactor = generatorIpFactor();

  private static long generatorRandomFactor(){
    return (long) (Math.random() * Math.pow(2.0D, 32.0D));
  }

  private static long generatorTimeFactor(){
    long timeStamp = System.currentTimeMillis()/1000;
    return timeStamp;
  }

  private static long generatorIpFactor() {
    List ips = TraceIdGenerator.getLocalIpList();
    String ipAddr = "127.0.0.1";
    if (ips == null) {
      return ip2long(ipAddr);
    } else {

      for (Object ip : ips) {
        String iptmp = (String) ip;
        if (!iptmp.equals("127.0.0.1")) {
          ipAddr = iptmp;
          break;
        }
      }

      return ip2long(ipAddr);
    }
  }


  private static long ip2long(String ip) {
    String[] ipGroups = ip.split("\\.");
    Integer[] ipInt = new Integer[4];

    for (int i = 0; i < ipGroups.length; ++i) {
      ipInt[i] = Integer.valueOf(ipGroups[i]);
    }

    int var5 = ipInt[0] << 24 | ipInt[1] << 16 | ipInt[2] << 8 | ipInt[3];
    return (long) var5;
  }

  public static String generatorSpanId(){
    long timeFactor = generatorTimeFactor();
    long randomFactor = generatorRandomFactor();
    long spanId = (ipFactor & timeFactor) << 32 | randomFactor;
    return Long.toHexString(spanId);
  }





}
